//送检单模板名称
var sampleFileVerList = [
    "temp/Nifty.jsp",//NIPT检测,DX0558
    "temp/deaf.jsp",//耳聋基因检测,DX0459
    "temp/HPV.jsp",//HPV检测,DX0532
    "temp/diping.jsp",//地贫筛查,DX0016
    "temp/sample1.jsp",//产前血清学筛查,BS0001
    "temp/akxChildGenTest.jsp",//新生儿疾病筛查,BS0002
    // "temp/sample2.jsp"//两癌登记表,BS0003
]

//送检单模板对应的送检单字段详情，fieldName：字段英文名，fieldValue：字段中文名
var fieldRow = {
    "temp/Nifty.jsp": [
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'customerName', fieldValue: '医院名称' },
        { fieldName: 'customerCode', fieldValue: '医院编码' },
        { fieldName: 'departments', fieldValue: '送检科室' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '姓名' },
        { fieldName: 'gestationalWeeks', fieldValue: '孕周' },
        { fieldName: 'idCard', fieldValue: '身份证号' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'birthDate', fieldValue: '生日' },
        { fieldName: 'createTime', fieldValue: '创建时间' },
        { fieldName: 'transfusionDate', fieldValue: '扫码采血时间' },
        { fieldName: 'sampleAge', fieldValue: '年龄' },
        { fieldName: 'bodyWeight', fieldValue: '体重' },
        { fieldName: 'bodyHeight', fieldValue: '身高' },
        { fieldName: 'lmp', fieldValue: '末次月经' },
        { fieldName: 'clinicalDiagnosis', fieldValue: '临床诊断' },
        { fieldName: 'doctorName', fieldValue: '医生姓名' },
        { fieldName: 'personalReproductiveHistory', fieldValue: '生育史' },
        { fieldName: 'naturalAbortionNum', fieldValue: '自然流产次数' },
        { fieldName: 'stillbirthNum', fieldValue: '死胎次数' },
        { fieldName: 'btypeAbnormal', fieldValue: 'b超异常' },
        { fieldName: 'btypeAbnormalDesc', fieldValue: 'b超异常描述' },
        { fieldName: 'pregnancy', fieldValue: '妊娠方式' },
        { fieldName: 'adosculation', fieldValue: '是否IVF' },
        { fieldName: 'oafNum', fieldValue: '畸形儿孕产史' },
        { fieldName: 'ckTestOther', fieldValue: '畸形儿类型' },
        { fieldName: 'abnormalPregnancyHistory', fieldValue: '不良孕产史' },
        { fieldName: 'gravidaKaryotype', fieldValue: '孕妇染色体' },
        { fieldName: 'husbandKaryotype', fieldValue: '丈夫染色体' },
        { fieldName: 'allogeneticTransfusion', fieldValue: '一年内异体输血' },
        { fieldName: 'cellularImmunity', fieldValue: '四周内异体细胞免疫' },
        { fieldName: 'surgicalTransplantation', fieldValue: '移植手术' },
        { fieldName: 'stemCell', fieldValue: '干细胞治疗' },
        { fieldName: 'pregnancyNum', fieldValue: '孕次' },
        { fieldName: 'produceNum', fieldValue: '产次' },
        { fieldName: 'btypeUltrasonic', fieldValue: '胎数' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'fileVer', fieldValue: '文件版本号' },
        { fieldName: 'sampleAge', fieldValue: '受检者年龄' },
        { fieldName: 'addressProvince', fieldValue: '省' },
        { fieldName: 'addressCity', fieldValue: '市' },
        { fieldName: 'addressCounty', fieldValue: '区' },
        { fieldName: 'addressTown', fieldValue: '街道' },
        { fieldName: 'familyAddress', fieldValue: '地址' },
        { fieldName: 'couponNum', fieldValue: '优惠券编码' },
     //   { fieldName: 'ownerIdCard', fieldValue: '样例身份证号' },
        { fieldName: 'sampleStatus', fieldValue: '样品状态' },
        { fieldName: 'reportId', fieldValue: '报告编号' },
        { fieldName: 'familyProduce', fieldValue: '家族史' },
        { fieldName: 'husbandPhoneNum', fieldValue: '丈夫电话' }
    ],
    "temp/deaf.jsp": [
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'customerName', fieldValue: '医院名称' },
        { fieldName: 'customerCode', fieldValue: '医院编码' },
        { fieldName: 'departments', fieldValue: '送检科室' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '姓名' },
        { fieldName: 'motherName', fieldValue: '母亲姓名' },
        { fieldName: 'birthDate', fieldValue: '出生日期' },
        { fieldName: 'nationaltily', fieldValue: '民族' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'husbandPhoneNum', fieldValue: '手机号码' },
        { fieldName: 'idCard', fieldValue: '母亲身份证号' },
        { fieldName: 'sampleSex', fieldValue: '性别' },
        { fieldName: 'createTime', fieldValue: '创建时间' },
        { fieldName: 'transfusionDate', fieldValue: '扫码采血时间' },
        { fieldName: 'neonatalCareType5', fieldValue: '新生儿监护类型' },
        { fieldName: 'neonatalCareType', fieldValue: '新生儿监护类型（nicu）' },
        { fieldName: 'pregnancyInfection', fieldValue: '母亲怀孕期感染' },
        { fieldName: 'pregnancyInfectionInfo', fieldValue: ',怀孕期间感染选择5' },
        { fieldName: 'consanguineousMarriage', fieldValue: '父母近亲结婚' },
        { fieldName: 'medicationHistory', fieldValue: '用药史（氨基糖苷类药物）' },
        { fieldName: 'familyDeafness', fieldValue: '耳聋家族史' },
        { fieldName: 'earDeformity', fieldValue: '耳部畸形（包括小耳、内耳畸形等）' },
        { fieldName: 'nativePlace', fieldValue: '籍贯' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'fileVer', fieldValue: '文件版本号' },
        // { fieldName: 'sampleAge', fieldValue: '受检者年龄' },
        { fieldName: 'ckTestOther', fieldValue: '产前送检单' },
        { fieldName: 'addressProvince', fieldValue: '省' },
        { fieldName: 'addressCity', fieldValue: '市' },
        { fieldName: 'addressCounty', fieldValue: '区' },
        { fieldName: 'addressTown', fieldValue: '街道' },
        { fieldName: 'familyAddress', fieldValue: '地址' },
        { fieldName: 'couponNum', fieldValue: '优惠券编码' },
        { fieldName: 'ownerIdCard', fieldValue: '样例身份证号' },
        { fieldName: 'sampleStatus', fieldValue: '样品状态' },
        { fieldName: 'reportId', fieldValue: '报告编号' },
        { fieldName: 'husbandPhoneNum', fieldValue: '丈夫电话' }
    ],
    "temp/HPV.jsp": [
        { fieldName: 'customerName', fieldValue: '送检单位名称' },
        { fieldName: 'customerCode', fieldValue: '客户编号' },
        { fieldName: 'departments', fieldValue: '送检科室' },
        { fieldName: 'doctorName', fieldValue: '送检医生' },
        { fieldName: 'sampleType', fieldValue: '样本类型' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '姓名' },
        { fieldName: 'sampleSex', fieldValue: '性别' },
        { fieldName: 'sampleAge', fieldValue: '年龄' },
        { fieldName: 'isMarried', fieldValue: '婚否' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'address', fieldValue: '现居住址' },
        { fieldName: 'postNum', fieldValue: '邮编' },
        { fieldName: 'hosptialNum', fieldValue: '门诊号/住院号' },
        { fieldName: 'idCard', fieldValue: '身份证号' },
        { fieldName: 'lmp', fieldValue: '末次月经' },
        { fieldName: 'clinicalDiagnosis', fieldValue: '临床诊断' },
        { fieldName: 'personalHistory', fieldValue: '既往病史' },
        { fieldName: 'couponNum', fieldValue: '免费券码' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'addressStreet', fieldValue: '街道' },
        { fieldName: 'createTime', fieldValue: '录入时间' },
        { fieldName: 'usedTime', fieldValue: '扫码采样日期' }
    ],
    "temp/diping.jsp": [
        { fieldName: 'customerName', fieldValue: '送检单位名称' },
        { fieldName: 'customerCode', fieldValue: '客户编号' },
        { fieldName: 'departments', fieldValue: '送检科室' },
        { fieldName: 'doctorName', fieldValue: '送检医生' },
        { fieldName: 'sampleType', fieldValue: '样本类型' },
        { fieldName: 'sampleTypeOther', fieldValue: '其他样本类型名称' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '姓名' },
        { fieldName: 'sampleSex', fieldValue: '性别' },
        { fieldName: 'sampleAge', fieldValue: '年龄' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'oldSampleNum', fieldValue: '原样品编号' },
        { fieldName: 'nationaltily', fieldValue: '民族' },
        { fieldName: 'nativePlace', fieldValue: '籍贯' },
        { fieldName: 'idCard', fieldValue: '身份证号' },
        { fieldName: 'hosptialNum', fieldValue: '住院号' },
        { fieldName: 'bedNum', fieldValue: '床号' },
        { fieldName: 'transfusionHistory', fieldValue: '是否有输血史' },
        { fieldName: 'transfusionDate', fieldValue: '输血时间' },
        { fieldName: 'clinicalExamination', fieldValue: '临床检查' },
        { fieldName: 'couponNum', fieldValue: '免费券码' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'addressStreet', fieldValue: '街道' },
        { fieldName: 'createTime', fieldValue: '录入时间' },
        { fieldName: 'usedTime', fieldValue: '扫码采样日期' }
    ],
    "temp/sample1.jsp": [
        { fieldName: 'customerName', fieldValue: '送检单位名称' },
        { fieldName: 'customerCode', fieldValue: '客户编号' },
        { fieldName: 'doctorName', fieldValue: '开单医生' },
        { fieldName: 'notes', fieldValue: '备注' },
        { fieldName: 'sampleType', fieldValue: '样本类型' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '姓名' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'idCard', fieldValue: '身份证号' },
        { fieldName: 'birthDate', fieldValue: '生日' },
        { fieldName: 'dnaMotherName', fieldValue: '母亲姓名' },
        { fieldName: 'dnaMotherIdCard', fieldValue: '母亲身份证' },
        { fieldName: 'motherPlace', fieldValue: '母亲户籍' },
        { fieldName: 'dnaFatherName', fieldValue: '父亲姓名' },
        { fieldName: 'dnaFatherIdCard', fieldValue: '父亲身份证号' },
        { fieldName: 'fatherPlace', fieldValue: '父亲户籍' },
        { fieldName: 'address', fieldValue: '联系地址' },
        { fieldName: 'bodyWeight', fieldValue: '体重' },
        { fieldName: 'lmp', fieldValue: '末次月经' },
        { fieldName: 'fetusNum', fieldValue: '胎儿个数' },
        { fieldName: 'identicalTwins', fieldValue: '同胎双生' },
        { fieldName: 'rule', fieldValue: '是否规则' },
        { fieldName: 'gestationalWeekFigure', fieldValue: '孕周计算方式' },
        { fieldName: 'btypeTime', fieldValue: 'B超时间' },
        { fieldName: 'btypeGestationalWeek', fieldValue: 'B超孕周' },
        { fieldName: 'lmpGestationalWeek', fieldValue: 'LMP孕周' },
        { fieldName: 'assistGestationalWeek', fieldValue: '辅助孕周' },
        { fieldName: 'crlFigure', fieldValue: 'CRL' },
        { fieldName: 'bpdFigure', fieldValue: 'BPD' },
        { fieldName: 'crlGestationalWeek', fieldValue: 'CRL孕周' },
        { fieldName: 'realGestationalWeek', fieldValue: '实际孕周' },
        { fieldName: 'crl2Figure', fieldValue: 'CRL2' },
        { fieldName: 'bpd2Figure', fieldValue: 'BPD2' },
        { fieldName: 'bpdGestationalWeek', fieldValue: 'BPD孕周' },
        { fieldName: 'assistAge', fieldValue: '辅助年龄' },
        { fieldName: 'edd', fieldValue: '预产年龄' },
        { fieldName: 'assistReproduction', fieldValue: '辅助生殖方法' },
        { fieldName: 'oocyteBirthday', fieldValue: '赠卵者生日' },
        { fieldName: 'extractAge', fieldValue: '提取年龄' },
        { fieldName: 'implantationDate', fieldValue: '植入日期' },
        { fieldName: 'extractDate', fieldValue: '提取日期' },
        { fieldName: 'ntFigure', fieldValue: 'NT参与计算' },
        { fieldName: 'nt1Value', fieldValue: 'NT1' },
        { fieldName: 'nt21Value', fieldValue: '2NT1' },
        { fieldName: 'nt2Value', fieldValue: 'NT2' },
        { fieldName: 'nt22Value', fieldValue: '2NT2' },
        { fieldName: 'nt3Value', fieldValue: 'NT3' },
        { fieldName: 'nt23Value', fieldValue: '2NT3' },
        { fieldName: 'nt1AvgValue', fieldValue: 'NT1均值' },
        { fieldName: 'nt2AvgValue', fieldValue: 'NT2均值' },
        { fieldName: 'smokingTag', fieldValue: '是否吸烟' },
        { fieldName: 'diabetesByInsulin', fieldValue: '是否胰岛素依赖性糖尿病：' },
        { fieldName: 'censusTag', fieldValue: '户籍' },
        { fieldName: 'identityInfo', fieldValue: '同身份证信息' },
        { fieldName: 'race', fieldValue: '种族' },
        { fieldName: 'uniteTag', fieldValue: '是否联合' },
        { fieldName: 'uniteValue', fieldValue: '联合方式' },
        { fieldName: 'screeningTag', fieldValue: '是否筛查' },
        { fieldName: 'screeningReason', fieldValue: '不筛查原因' },
        { fieldName: 'personalHistory', fieldValue: '已往病史' },
        { fieldName: 'otherDiseaseHistory', fieldValue: '其他已往病史描述' },
        { fieldName: 'abnormalType', fieldValue: '异常类型' },
        { fieldName: 'patientNum', fieldValue: '病历号' },
        { fieldName: 'couponNum', fieldValue: '免费券码' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'addressStreet', fieldValue: '街道' },
        { fieldName: 'createTime', fieldValue: '录入时间' },
        { fieldName: 'usedTime', fieldValue: '扫码采样日期' }
    ],
    "temp/akxChildGenTest.jsp": [
        { fieldName: 'customerName', fieldValue: '送检单位名称' },
        { fieldName: 'customerCode', fieldValue: '客户编号' },
        { fieldName: 'doctorName', fieldValue: '医生姓名' },
        { fieldName: 'sampleType', fieldValue: '样本类型' },
        { fieldName: 'bloodDate', fieldValue: '采样日期' },
        { fieldName: 'sampleName', fieldValue: '受检者姓名' },
        { fieldName: 'sampleSex', fieldValue: '性别' },
        { fieldName: 'birthDate', fieldValue: '出生日期' },
        { fieldName: 'personType', fieldValue: '受检者类型' },
        { fieldName: 'nationaltily', fieldValue: '民族' },
        { fieldName: 'nativePlace', fieldValue: '籍贯' },
        { fieldName: 'guardianShip', fieldValue: '监护人姓名' },
        { fieldName: 'motherPhoneNum', fieldValue: '联系电话' },
        { fieldName: 'sampleRecipientEmail', fieldValue: '电子邮箱/地址' },
        { fieldName: 'idCard', fieldValue: '身份证号' },
        { fieldName: 'reportAddress', fieldValue: '报告发送地址' },
        { fieldName: 'clinicalManifestation', fieldValue: '临床表现' },
        { fieldName: 'bear24Hour', fieldValue: '产后24小时' },
        { fieldName: 'bodyWeight', fieldValue: '出生时体重' },
        { fieldName: 'bodyHeight', fieldValue: '身高（出生时体长）' },
        { fieldName: 'apgar', fieldValue: 'apgar评分' },
        { fieldName: 'suckler72', fieldValue: '出生72小时后并充分哺乳' },
        { fieldName: 'deliveryMode', fieldValue: '分娩方式' },
        { fieldName: 'motherName', fieldValue: '母亲姓名' },
        { fieldName: 'motherAge', fieldValue: '母亲年龄' },
        { fieldName: 'dnaFatherName', fieldValue: '父亲姓名' },
        { fieldName: 'fatherAge', fieldValue: '父亲年龄' },
        { fieldName: 'familyProduce', fieldValue: '家族史' },
        { fieldName: 'couponNum', fieldValue: '免费券码' },
        { fieldName: 'productName', fieldValue: '产品名称' },
        { fieldName: 'productCode', fieldValue: '产品编号' },
        { fieldName: 'sampleBaseId', fieldValue: '样本编号' },
        { fieldName: 'addressStreet', fieldValue: '街道' },
        { fieldName: 'createTime', fieldValue: '录入时间' },
        { fieldName: 'usedTime', fieldValue: '扫码采样日期' }
    ]
}

//特殊字段对应关系
var compareFields = {
    sampleSex: { "0": "未知", "1": "男", "2": "女" },
    pregnancy: { "0": "自然受孕", "1": "促排卵", "2": "宫内人工受精" , "3": "其他" },
    pregnancyInfection: { "0": "无", "1": "有" },
    consanguineousMarriage: { "0": "无", "1": "有" },
    medicationHistory: { "0": "否", "1": "是" },
    familyDeafness: { "0": "无", "1": "有" },
    earDeformity: { "0": "否", "1": "是" },
    adosculation: { "0": "否", "1": "是" },
    abnormalPregnancyHistory: { "0": "无", "1": "有" },
    ntd: { "0": "未做", "1": "已做（高风险）", "2": "已做（低风险）" },
    gravidaKaryotype: { "0": "未做", "1": "正常", "2": "异常" },
    husbandKaryotype: { "0": "未做", "1": "正常", "2": "异常" },
    allogeneticTransfusion: { "0": "无", "1": "有（不接受）" },
    cellularImmunity: { "0": "无", "1": "有（不接受）" },
    surgicalTransplantation: { "0": "无", "1": "有（不接受）" },
    stemCell: { "0": "无", "1": "有（不接受）" },
    sampleType: { "01": "全血", "03": "DNA", "05": "干血片", "08": "口腔拭子", "18": "唾液", "32": "其他", "101": "正常样本", "102": "重采样本" },
    btypeUltrasonic: { "0": "单胎", "1": "双胎", "2": "三胎"},
    screeningModel: { "0": "未做", "1": "nt筛查", "2": "早孕期筛查", "3": "中孕期筛查", "4": "早中孕期联合筛查" },
    motherSerumRisk: { "0": "高风险", "1": "临界风险", "2": "低风险" },
    transfusionHistory: { "0": "是", "1": "否" },
    identicalTwins: { "0": "否", "1": "是" },
    rule: { "0": "否", "1": "是" },
    ntFigure: { "0": "否", "1": "是" },
    smokingTag: { "0": "否", "1": "是" },
    diabetesByInsulin: { "0": "否", "1": "是" },
    censusTag: { "0": "省外", "1": "省内" },
    race: { "0": "默认", "1": "加勒比海人", "2": "高加索" },
    uniteValue: { "0": "中孕三联", "1": "中孕二联", "2": "早孕三联", "3": "早孕二联+NT" },
    suckler72: { "0": "否", "1": "是" },
    deliveryMode: { "0": "平产", "1": "剖腹产" },
    neonatalCareType:{"0":"普通病房","1":"新生儿黄疸","2":"新生儿肺炎","3":"新生儿早产/低体重儿","4":" 呛到羊水","5":"其他"},
    sampleStatus:{"0":"未采样","1":"已采样"},
    oafNum:{"0":"无","1":"有"},
    ckTestOther:{"0":"13三体","1":"18三体","2":"21三体","3":"神经管缺陷","4":"其他"}
};

function tablesToExcel(parentEle, wsnames, wbname, appname) {
    var uri = 'data:application/vnd.ms-excel;base64,'
        , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
        + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Benjamin BACKX</Author><Created>{created}</Created></DocumentProperties>'
        + '<Styles>'
        + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
        + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
        + '</Styles>'
        + '{worksheets}</Workbook>'
        , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
        , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
        , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
        , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";
    var tables = parentEle.querySelectorAll('table');
    for (var i = 0; i < tables.length; i++) {
        if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
        for (var j = 0; j < tables[i].rows.length; j++) {
            ((rowEles, iValue, jValue) => {
                setTimeout(() => {
                rowsXML += '<Row>';
                for (var k = 0; k < rowEles[jValue].cells.length; k++) {
                    var dataType = rowEles[jValue].cells[k].getAttribute("data-type");
                    var dataStyle = rowEles[jValue].cells[k].getAttribute("data-style");
                    var dataValue = rowEles[jValue].cells[k].getAttribute("data-value");
                    dataValue = (dataValue) ? dataValue : rowEles[jValue].cells[k].innerHTML;
                    var dataFormula = rowEles[jValue].cells[k].getAttribute("data-formula");
                    dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
                    ctx = {
                        attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : ''
                        , nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String'
                        , data: (dataFormula) ? '' : dataValue
                        , attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
                    };
                    rowsXML += format(tmplCellXML, ctx);
                }
                rowsXML += '</Row>';
                if (jValue == rowEles.length - 1) {
                    ctx = { rows: rowsXML, nameWS: wsnames[iValue] || 'Sheet' + iValue };
                    worksheetsXML += format(tmplWorksheetXML, ctx);
                    rowsXML = "";
                }
                if (jValue == rowEles.length - 1 && iValue == tables.length - 1) {
                    ctx = { created: (new Date()).getTime(), worksheets: worksheetsXML };
                    workbookXML = format(tmplWorkbookXML, ctx);
                    var blob = new Blob([workbookXML], { type: 'application/vnd.ms-excel' });
                    saveAs(blob, wbname);
                    setTimeout(() => {
                        window.sessionStorage.setItem('exportFinished', 1);
                }, 1000);
                }
            }, 50)
        })(tables[i].rows, i, j)
        }
    }

}

//送检单列表导出excel
function exportSampleExcel(tableDataList) {
    if (!tableDataList) {
        window.sessionStorage.setItem('exportFinished', 1);
        return;
    }
    //送检单数据列表
    var data = {
        "temp/Nifty.jsp": [],
        "temp/deaf.jsp": [],
        "temp/HPV.jsp": [],
        "temp/diping.jsp": [],
        "temp/sample1.jsp": [],
        "temp/akxChildGenTest.jsp": []
    };

    //excel表格的sheet名称
    var sheetNames = [];

    var tables = '';
    Object.keys(data).forEach(key => {
        data[key] = tableDataList
            .filter(item => item.fileVer === key)
.map(item => {
        //默认先将所有的字段的值都初始化成空字符串
        var relItem = {};
        fieldRow[key].forEach(field => {
            relItem[field.fieldName] = '';
        });
    //设置字段的真实值
    Object.keys(item).forEach(k => {
        if (relItem[k] === '') {
        var v = item[k];
        if (compareFields[k]) {
            v = compareFields[k][v + ''];
        }
        relItem[k] = v;
    }

});
    return relItem
});

    if (data[key].length > 0) {
        sheetNames.push(data[key][0].productName);
        var thDatas = fieldRow[key].map(item => item.fieldValue);
        var thFields = fieldRow[key].map(item => item.fieldName);
        var mData = {};
        mData.ths = fieldRow[key];
        mData.trs = [];
        for (var i = 0; i < data[key].length; i++) {
            var sample = data[key][i];
            var arr = Object.keys(sample).map(key => sample[key]);
            mData.trs[i] = arr;
        }
        var html = template('table', mData);
        tables += html;
    }
});

    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables;
        tablesToExcel(ele, sheetNames, '送检单' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

var couponFields = [
    { fieldName: 'name', fieldValue: '姓名' },
    { fieldName: 'id', fieldValue: '身份证号' },
    { fieldName: 'mobile', fieldValue: '手机号' },
    { fieldName: 'province', fieldValue: '省份' },
    { fieldName: 'city', fieldValue: '城市' },
    { fieldName: 'country', fieldValue: '区/县' },
    { fieldName: 'town', fieldValue: '街道' },
    { fieldName: 'sex', fieldValue: '性别' },
    { fieldName: 'nation', fieldValue: '民族' },
    { fieldName: 'birth', fieldValue: '出生日期' },
    { fieldName: 'address', fieldValue: '家庭住址' },
    { fieldName: 'couponName', fieldValue: '免费券类型' },
    { fieldName: 'presonType', fieldValue: '免费类型' },
    { fieldName: 'status', fieldValue: '状态' },
    { fieldName: 'couponNum', fieldValue: '优惠券码' },
    { fieldName: 'createTime', fieldValue: '申请日期' },
    { fieldName: 'receiveTime', fieldValue: '领取时间' },
    { fieldName: 'productCode', fieldValue: '产品编号' },
    { fieldName: 'createTime', fieldValue: '创建日期' },
    { fieldName: 'openId', fieldValue: 'openId' },
    { fieldName: 'imgs', fieldValue: '证件照' },
];
var realValueForCouponFields = {
    presonType: { '1': '本人为长沙户口', '2': '配偶为长沙户口', '3': '长沙居住证', '4': '军人及军人配偶' },
    status: { '1': '审批通过', '0': '审批中', '-1': '未审批通过', '2': '已使用', '3': '已绑定' }
};
//优惠券用户列表导出excel
function exportCouponExcel(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        var imgs = [];
        if (item.cardFrontImgUrl) {
            imgs.push(window.location.origin + item.cardFrontImgUrl);
        }
        if (item.marriageImgUrl) {
            imgs.push(window.location.origin + item.marriageImgUrl);
        }
        if (item.cardMateImgUrl) {
            imgs.push(window.location.origin + item.cardMateImgUrl);
        }
        if (item.officerImgUrl) {
            imgs.push(window.location.origin + item.officerImgUrl);
        }
        if (item.residencePermitImgUrl) {
            imgs.push(window.location.origin + item.residencePermitImgUrl);
        }
        if (item.familyRegisterImgUrl) {
            imgs.push(window.location.origin + item.familyRegisterImgUrl);
        }
        item.imgs = imgs.join('\r\n');
        return item;
    });
    var mData = {};
    mData.ths = couponFields;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = couponFields.map(item => item.fieldName).map(key => {
        return realValueForCouponFields[key] ? realValueForCouponFields[key][listItem[key]] : listItem[key]
    })
});
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables;
        tablesToExcel(ele, '优惠券', '优惠券' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//街道优惠券使用统计导出
var streetCoupons = [
    { fieldName: 'country', fieldValue: '区/县' },
    { fieldName: 'town', fieldValue: '街道' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检查' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' }
];
function exportStreetCoupons(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = streetCoupons;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = streetCoupons.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '街道优惠券使用统计', '街道优惠券使用统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1)
    }
}

//机构扫码量统计
var institutionsCoupons = [
    { fieldName: 'country', fieldValue: '区/县' },
    { fieldName: 'customerName', fieldValue: '扫码机构' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检查' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' }
];
function exportInstitutionsCoupons(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = institutionsCoupons;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = institutionsCoupons.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '机构扫码量统计', '机构扫码量统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1)
    }
}

//产筛新筛机构------样本接收量统计
var institutionSampleTotal = [
    { fieldName: 'customerName', fieldValue: '采血医院' },
    { fieldName: 'inspectionAgencyName', fieldValue: '检测机构' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检查' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' }
];
function exportInstitutionSampleTotal(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = institutionSampleTotal;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = institutionSampleTotal.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '机构样本接收量统计', '机构样本接收量统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1)
    }
}

//检测机构样本统计量-----区域统计
var institutionsCountryTotal = [
    { fieldName: 'country', fieldValue: '区县' },
    { fieldName: 'inspectionAgencyName', fieldValue: '检测机构' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检查' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' }
];
function exportInstitutionsCountryTotal(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = institutionsCountryTotal;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = institutionsCountryTotal.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables;
        tablesToExcel(ele, '检测机构样本统计量--区域统计', '检测机构样本统计量--区域统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//检测机构----检测量统计
var institutionsTotal = [
    { fieldName: 'country', fieldValue: '区县' },
    { fieldName: 'inspectionAgencyName', fieldValue: '检测机构' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检查' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' }
];
function exportInstitutionsTotal(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = institutionsTotal;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = institutionsTotal.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables;
        tablesToExcel(ele, '检测机构--检测量统计', '检测机构--检测量统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//医院级详情导出
var hospitalAccount = [
    { fieldName: 'presonName', fieldValue: '姓名' },
    { fieldName: 'presonNation', fieldValue: '民族' },
    { fieldName: 'presonSex', fieldValue: '性别' },
    { fieldName: 'presonType', fieldValue: '免费类型' },
    { fieldName: 'couponBaseName', fieldValue: '检测类型' },
    { fieldName: 'couponCode', fieldValue: '优惠券号码' },
    { fieldName: 'scannerHospital', fieldValue: '扫码人' },
    // { fieldName: 'mobile', fieldValue: '手机号码' },
    { fieldName: 'customerName', fieldValue: '采血机构' },
    { fieldName: 'inspectionAgencyName', fieldValue: '检测机构' },
    { fieldName: 'receiveTime', fieldValue: '领取日期' },
    { fieldName: 'usedTime', fieldValue: '使用时间' },
    { fieldName: 'city', fieldValue: '市' },
    { fieldName: 'country', fieldValue: '区/县' },
    { fieldName: 'town', fieldValue: '街道' }
];
function exportHospitalAccount(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = hospitalAccount;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = hospitalAccount.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '免费券--医院级详情', '免费券--医院级详情' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//区县级统计
var summary = [
    { fieldName: 'customerName', fieldValue: '机构名称' },
    { fieldName: 'DX0459', fieldValue: '耳聋基因检测' },
    { fieldName: 'DX0558', fieldValue: 'NIPT检测' },
    { fieldName: 'DX0532', fieldValue: 'HPV检测' },
    { fieldName: 'BS0001', fieldValue: '产前血清学筛查' },
    { fieldName: 'BS0002', fieldValue: '新生儿疾病筛查' },
    { fieldName: 'DX0016', fieldValue: '地中海贫血基因检测' }
];
function exportSummaryExcel(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = summary;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = summary.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '免费券--区县统计级', '免费券--区县统计级' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//区县级详情
var countyInfo = [
    { fieldName: 'presonName', fieldValue: '姓名' },
    { fieldName: 'customerName', fieldValue: '采血机构' },
    { fieldName: 'inspectionAgencyName', fieldValue: '检测机构' },
    { fieldName: 'receiveTime', fieldValue: '领取日期' },
    { fieldName: 'usedTime', fieldValue: '使用时间' },
    { fieldName: 'country', fieldValue: '区/县' },
    { fieldName: 'town', fieldValue: '街道' },
    { fieldName: 'couponBaseName', fieldValue: '免费券类型' }
];
function exportCountyInfoExcel(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = countyInfo;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = countyInfo.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '免费券--区县详情', '免费券--区县详情' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//医院级导出TOP
var testReportTop = [
    { fieldName: 'country', fieldValue: '区县' },
    { fieldName: 'DX0459合计', fieldValue: '耳聋基因检测数' },
    { fieldName: 'DX0558合计', fieldValue: 'NIPT检测数' },
    // { fieldName: 'DX0532', fieldValue: 'HPV检测数' },
    { fieldName: 'BS0001合计', fieldValue: '产前血清学筛查检测数' },
    { fieldName: 'BS0002合计', fieldValue: '新生儿疾病筛查检测数' },
    // { fieldName: 'DX0016', fieldValue: '地中海贫血基因检测数' }
    { fieldName: '总计', fieldValue: '总计' },
];
function exportTestReportTopExcel(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = testReportTop;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = testReportTop.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '免费券--医院级--区县用券统计', '免费券--医院级--区县用券统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}

//医院级导出bottom
var testReportBottom = [
    { fieldName: 'country', fieldValue: '区县' },
    { fieldName: 'customerName', fieldValue: '采血医院' },
    { fieldName: 'DX0459合计', fieldValue: '耳聋基因检测数' },
    { fieldName: 'DX0558合计', fieldValue: 'NIPT检测数' },
    // { fieldName: 'DX0532', fieldValue: 'HPV检测数' },
    { fieldName: 'BS0001合计', fieldValue: '产前血清学筛查检测数' },
    { fieldName: 'BS0002合计', fieldValue: '新生儿疾病筛查检测数' }
    // { fieldName: 'DX0016', fieldValue: '地中海贫血基因检测数' }
];
function exportTestReportBottomExcel(dataList) {
    if (!dataList || !dataList.length) {
        window.sessionStorage.setItem('exportFinished', 1);
        return false;
    }
    var list = dataList.map(item => {
        return item;
    });
    var mData = {};
    mData.ths = testReportBottom;
    mData.trs = [];
    list.forEach((listItem, index) => {
        mData.trs[index] = testReportBottom.map(item => item.fieldName).map(key => {
            return listItem[key];
        })
    });
    var tables = template('table', mData) || '';
    if (tables) {
        var ele = document.createElement('div');
        ele.innerHTML = tables
        tablesToExcel(ele, '免费券--医院级--医院用券统计', '免费券--医院级--医院用券统计' + (new Date().getTime()) + '.xls', 'Excel');
    } else {
        window.sessionStorage.setItem('exportFinished', 1);
    }
}